<template>
  <div>
    <x-Table
      :loading="loading"
      :table-data="tableData"
      :options-data="options"
      :rule-form="ruleForms"
      :pagination="pagination"
      @handleAdd="handleAdd"
      @handlePaginationCurrentChange="handlePaginationCurrentChange"
      @handlePaginationSizeChange="handlePaginationSizeChange"
      @handleHeardDel="handleHeardDel"
      @searchForm="searchForm"
      @handleHeardEdit="handleHeardEdit"
      @resetForm="resetForm"

    >
      <el-table-column
        slot="roles"
        label="角色"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-tag>
            {{ arrayToObj(scope.row.roles) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        slot="sex"
        label="性别"
        align="center"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.sex === 1"> 男</el-tag>
          <el-tag v-if="scope.row.sex === 0" type="success"> 女</el-tag>
        </template>
      </el-table-column>
    </x-Table>

    <!--    弹窗区域-->
    <el-dialog
      v-dialog-drag
      :title="alertTitle"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="45%"
    >
      <form-create
        v-model="fapi"
        :rule="rule"
        :option="option"
        :value.sync="formParam"
        @submit="onSubmit"
      >

      </form-create>
    </el-dialog>
    <!--    end-->
  </div>
</template>

<script>
let _this;
export default {
  data() {
    return {
      searchParams: {},//搜索对象
      row: null,
      loading: true,
      pagination: {
        currentPage: 1,
        pageSize: 20,
        pageSizes: [10, 20, 50, 100],
      }, //分页参数
      fapi: {},
      formParam: {},
      rule: [
        {
          type: "select",
          field: "role",
          title: "角色",
          info: "",
          effect: {
            fetch: {
              action:
                "http://www.free.com/adminapi/v1.setting.admin.SystemRole/index",
              to: "options",
              method: "POST",
              parse(res) {
                return res.data.data.map((row) => {
                  return {
                    label: row.title,
                    value: row.id,
                  };
                });
              },
            },
          },
          options: [],
          _fc_drag_tag: "select",
          hidden: false,
          display: true,
        },
        {
          type: "input",
          field: "user",
          title: "用户名称",
          info: "",
          _fc_drag_tag: "input",
          hidden: false,
          display: true,
          props: {
            placeholder: "请书用户名称",
          },
        },
        {
          type: "input",
          field: "account",
          title: "账户名称",
          info: "",
          _fc_drag_tag: "input",
          hidden: false,
          display: true,
          props: {
            placeholder: "请输入账户名称",
          },
          validate: [
            {
              trigger: "submit",
              mode: "required",
              message: "请输入账户名称",
              required: true,
              type: "string",
            },
          ],
        },
        {
          type: "input",
          field: "pwd",
          title: "密码",
          info: "",
          props: {
            placeholder: "请输入密码",
          },
          _fc_drag_tag: "input",
          hidden: false,
          display: true,
          validate: [
            {
              trigger: "submit",
              mode: "required",
              message: "请输入密码",
              required: true,
              type: "string",
            },
          ],
        },
        {
          type: "radio",
          field: "sex",
          title: "性别",
          info: "",
          effect: {
            fetch: "",
          },
          options: [
            {
              value: 1,
              label: "男",
            },
            {
              value: 0,
              label: "女",
            },
          ],
          _fc_drag_tag: "radio",
          hidden: false,
          display: true,
        },
        {
          type: "input",
          field: "phone",
          title: "手机号码",
          info: "",
          _fc_drag_tag: "input",
          hidden: false,
          display: true,
          props: {
            maxlength: 11,
            minlength: 11,
            placeholder: "请输入手机号码",
            clearable: true,
          },
        },
        {
          type: "switch",
          field: "status",
          title: "状态",
          info: "",
          _fc_drag_tag: "switch",
          hidden: false,
          display: true,
        },
      ],
      option: {
        form: {
          inline: false,
          labelPosition: "right",
          size: "small",
          labelWidth: "125px",
          hideRequiredAsterisk: false,
          showMessage: true,
          inlineMessage: false,
        },
        resetBtn: true,
      },
      dialogVisible: false,
      alertTitle: "添加",
      tableData: [],
      options: {
        fields: {
          id: {label: "ID", prop: "id", width: "120", order: true},
          role: {label: "角色", prop: "roles", type: "slot", slot: "roles"},
          user: {label: "用户名称", prop: "name"},
          account: {label: "账户名称", prop: "account"},
          sex: {label: "性别", prop: "sex", slot: "sex", type: "slot"},
          phone: {label: "手机号", prop: "tel"},
          status: {
            label: "状态",
            prop: "status",
            type: "switch",
            activeValue: true,
            inactiveValue: false,
            switchChage: function (scope) {
            },
          },
          create_at: {label: "创建时间", prop: "create_time", order: true},
          button: {
            label: "操作",
            width: "130",
            type: "func",
            fixed: true,
            edit: function (scope) {
              _this.row = scope["row"];
              _this.alertTitle = "编辑";
              _this.dialogVisible = true;
              setTimeout(() => {
                _this.fapi.setValue("user", scope["row"].name);
                _this.fapi.setValue(
                  "role",
                  scope["row"].roles.length > 0 ? scope["row"].roles[0].id : ""
                );
                _this.fapi.setValue("account", scope["row"].account);
                _this.fapi.setValue("pwd", scope["row"].password);
                _this.fapi.setValue("status", scope["row"].status);
                _this.fapi.setValue("phone", scope["row"].tel);
                _this.fapi.setValue("sex", scope["row"].sex);
                _this.fapi.setValue("status", scope["row"].status);
              }, 0);
            },
            del: function (scope) {
              _this.delUser(scope['row'].id)
            },
          },
        },
      },
      ruleForms: {
        account: {label: "账户名称", prop: "account", type: "text"},
      },
    };
  },
  methods: {
    arrayToObj: function (arrayObj) {
      if (arrayObj.length === 0) {
        return "无";
      } else {
        return arrayObj[0]["title"];
      }
    },
    handlePaginationCurrentChange: function (val) {
      _this.pagination["currentPage"] = val;
      _this.searchAccount(_this.searchParams);
    },
    handlePaginationSizeChange: function (val) {
      _this.pagination["pageSize"] = val;
      _this.searchAccount(_this.searchParams);
    },
    handleHeardDel: function (val) {
      let data = [];
      val.forEach((item, index) => {
        data.push(item.id)
      })
      _this.delUser(data.join());
    },
    resetForm: function () {
      _this.searchParams = {};
    },
    searchForm: function (val) {
      _this.searchParams = val
      _this.searchAccount(val);
    },
    handleHeardEdit: function (val) {
      // _this.delUser(val);
    },

    getUserList: function () {
      this.$store
        .dispatch("admin/setAdminList", {
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        })
        .then(() => {
          _this.loading = false;
          _this.dialogVisible = false;
          let data = this.$store.state.admin.adminList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        });
    },

    searchAccount: function (val) {
      this.$store
        .dispatch("admin/searchAccount", {
          account: val['account'],
          page: _this.pagination["currentPage"],
          pageSize: _this.pagination["pageSize"],
        })
        .then(() => {
          _this.dialogVisible = false;
          let data = this.$store.state.admin.adminList;
          this.tableData = data.data;
          _this.pagination["currentPage"] = data["current_page"];
          _this.pagination["total"] = data["total"];
        })
    },

    updateAdmin: function (val) {
      _this.$store.dispatch('admin/updateAdmin', {
        id: _this.row['id'],
        name: val["user"],
        account: val["account"],
        password: val["pwd"],
        sex: val["sex"],
        tel: val["phone"],
        status: val["status"],
        role: val["role"],
      }).then(res => {
        const {data, msg} = res;
        if (data) {
          _this.$message.success(msg);
          _this.getUserList();
        } else {
          _this.$message.error(msg);
        }
      })
    },
    delUser: function (val) {
      _this.$store.dispatch('admin/delAdmin', {
        id: val
      }).then(res => {
        const {data, msg} = res;
        if (data) {
          _this.$message.success(msg);
          _this.getUserList();
        } else {
          _this.$message.error(msg);
        }
      })
    },

    /**
     * 保存用户
     */
    saveUser: function (val) {
      this.$store
        .dispatch("admin/addAdmin", {
          name: val["user"],
          account: val["account"],
          password: val["pwd"],
          sex: val["sex"],
          tel: val["phone"],
          status: val["status"],
          role: val["role"],
        })
        .then((res) => {
          const {data, msg} = res;
          if (data === 1) {
            _this.$message.success(msg);
            _this.getUserList();
          } else {
            _this.$message.error(msg);
          }
        });
    },

    /**
     * 表单提交回调
     */
    onSubmit: function (val) {
      if (_this.alertTitle === "添加") {
        _this.saveUser(val);
      } else {
        _this.updateAdmin(val);
      }
    },

    /**
     *  添加添加
     */
    handleAdd: function () {
      _this.alertTitle = "添加";
      _this.dialogVisible = true;
    },
  },
  watch: {
    dialogVisible(newVal) {
      setTimeout(() => {
        if (!newVal) {
          _this.fapi.resetFields(); //清空数据
        }
      }, 0);
    },
  },
  mounted() {
    _this.getUserList();
  },
  created() {
    _this = this;
    console.log(this.$route);
    console.log(this.$store.state.routes.routes);
  },
};
</script>

<style scoped></style>
